package com.cqw.mq;

import com.alibaba.fastjson.JSON;
import com.cqw.common.UUID;
import com.cqw.constant.MqConstant;
import com.cqw.domain.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-04-15 14:11
 * @Description: 消息提供者
 */
@Component
@Slf4j
public class MqProvider {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    public void initArea() {
        //rabbitTemplate.convertAndSend(MqConstant.AREA_EX, MqConstant.AREA_KEY, "123");
        log.info("初始化区域消息发送成功");
    }


    public void ceShi() {
        SysUser user = new SysUser();
        user.setUserId(1L);
        user.setUserName("曹青稳");
        rabbitTemplate.convertAndSend(MqConstant.CE_SHI_EX, MqConstant.CE_SHI_KEY, JSON.toJSONString(user));
        log.info("测试消息发送成功");
    }


    public void sendLog(String message) {
        try {
            log.info("发送日志消息：{}", message);
            rabbitTemplate.convertAndSend(MqConstant.LOG_EX, MqConstant.LOG_KEY, message);
        } catch (AmqpException e) {
            log.error("发送日志消息失败，消息体：{}", message);
        }
    }


    //==============================下面是测试几种模式start


    /**
     * 直连模式，直接发送到队列，没有交换机
     */
    public void model1() {
        rabbitTemplate.convertAndSend("hello", "hello world");
    }


    /**
     * 广播模式，一个交换机，多个队列绑定到一个交换机上，消费者都能接收到消息
     */
    public void model2() {
        rabbitTemplate.convertAndSend("logs", null, "广播日志");
    }

    /**
     * direct模式：一个交换机，根据不同的路由key，路由到不同的队列中
     */
    public void model3() {
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("directExchange", "info", "info消息", correlationData);
        //rabbitTemplate.convertAndSend("directExchange", "error", "error消息");
    }

    /**
     * topic模式：* 匹配一个字符，# 匹配0个或多个字符
     */
    public void model4() {
        rabbitTemplate.convertAndSend("topicExchange", "user", "user 的消息");
        rabbitTemplate.convertAndSend("topicExchange", "user.save", "user.save 的消息");
        rabbitTemplate.convertAndSend("topicExchange", "user.save.findAll", "user.save.findAll 的消息");
    }

    /**
     * 死信队列发消息
     */
    public void model5() {
        rabbitTemplate.convertAndSend("deadly", (Object) "延时消息", message -> {
            //可以设置消息的存活时间
            message.getMessageProperties().setExpiration("10000");
            message.getMessageProperties().setMessageId("caoqingwen");
            return message;
        });
    }


}
